package com.ainibaby6.utils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

public class SessionUtil
{
    public static final String SESSION_CREATE_TIME = "Session_Key_CREATE_TIME";

    private static Map<String, Map<String, Object>> sessionMap = new ConcurrentHashMap<String, Map<String, Object>>();

    public static String addSession()
    {
        String sid = UUID.randomUUID().toString();
        Map<String, Object> map = new HashMap<String, Object>();
        // 初始化
        map.put(SESSION_CREATE_TIME, new Date());

        sessionMap.put(sid, map);
        return sid;
    }

    public static void removeSession(String sid)
    {
        sessionMap.remove(sid);
    }

    public static <T> T getAttr(String sid, String key)
    {
        Map<String, Object> map = sessionMap.get(sid);
        if (map == null)
        {
            return null;
        }
        return (T) map.get(key);
    }

    public static boolean addAttr(String sid, String key, Object value)
    {
        Map<String, Object> map = sessionMap.get(sid);
        if (map == null)
        {
            return false;
        }
        map.put(key, value);
        return true;
    }

    public static Object deleteAttr(String sid, String key)
    {
        Map<String, Object> map = sessionMap.get(sid);
        if (map == null)
        {
            return null;
        }
        return map.remove(key);
    }

    public static boolean checkSession(String sid)
    {
        return sessionMap.containsKey(sid);
    }
}
